package cn.broadsense.web.controller;

import cn.broadsense.biz.domain.CollectDataTask;
import cn.broadsense.biz.service.CollectDataTaskService;
import cn.broadsense.common.constant.HttpStatus;
import cn.broadsense.common.core.controller.BaseController;
import cn.broadsense.common.core.domain.R;
import cn.broadsense.common.core.domain.entity.SysUser;
import cn.broadsense.common.core.page.TableDataInfo;
import cn.broadsense.common.utils.SecurityUtils;
import cn.broadsense.system.domain.SysNotice;
import cn.broadsense.system.domain.SysUserNotice;
import cn.broadsense.system.service.ISysNoticeService;
import cn.broadsense.system.service.ISysUserNoticeService;
import cn.broadsense.system.service.ISysUserService;
import cn.broadsense.web.controller.body.NoticeSwitchBody;
import cn.broadsense.web.controller.query.NoticeQuery;
import cn.broadsense.web.controller.vo.NoticeSettingVO;
import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author huangjinshi
 * @description
 * @createDate 2023-09-14 11:23:09
 */

@Slf4j
@Api(tags = "消息管理模块")
@RestController
@RequestMapping("")
public class NoticeController extends BaseController {

    @Autowired
    public ISysNoticeService sysNoticeService;

    @Autowired
    private ISysUserNoticeService sysUserNoticeService;

    @Autowired
    private CollectDataTaskService collectDataTaskService;

    @Autowired
    private ISysUserService userService;


    @ApiOperation("获取未读消息数")
    @GetMapping("/api/v1/notice/unread")
    public R<Long> getUnreadCount() {
        List<SysNotice> list = sysNoticeService.selectNoticeListByUserId(SecurityUtils.getUserId());
        for (SysNotice item : list) {
            SysUserNotice userNotice = sysUserNoticeService.getByUserIdAndNoticeId(SecurityUtils.getUserId(), item.getNoticeId());
            if (userNotice == null) {
                item.setReadStatus(0);
            } else {
                item.setReadStatus(userNotice.getStatus());
            }
        }
        long count = list.stream().filter(sysNotice -> 0 == sysNotice.getReadStatus()).count();
        return R.ok(count);
    }

    @ApiOperation("获取消息列表")
    @GetMapping("/api/v1/notice/list")
    public R<List<SysNotice>> getList() {
        List<SysNotice> noticeList = sysNoticeService.selectNoticeListByUserId(SecurityUtils.getUserId());
        for (SysNotice notice : noticeList) {
            SysUserNotice userNotice = sysUserNoticeService.getByUserIdAndNoticeId(SecurityUtils.getUserId(), notice.getNoticeId());
            if (userNotice == null) {
                notice.setReadStatus(0);
            } else {
                notice.setReadStatus(userNotice.getStatus());
            }
        }
        return R.ok(noticeList);
    }

    @ApiOperation("获取消息列表（分页）")
    @GetMapping("/api/v2/notice/list")
    public TableDataInfo getPageList(NoticeQuery query) {
        SysNotice sysNotice = SysNotice.builder().noticeTitle(query.getNoticeTitle()).userId(SecurityUtils.getUserId()).build();

        startPage();
        List<SysNotice> list = sysNoticeService.getList(sysNotice);
        for (SysNotice item : list) {
            SysUserNotice userNotice = sysUserNoticeService.getByUserIdAndNoticeId(SecurityUtils.getUserId(), item.getNoticeId());
            if (userNotice == null) {
                item.setReadStatus(0);
            } else {
                item.setReadStatus(userNotice.getStatus());
            }
            if (item.getRelationModule().equals(1)) {
                CollectDataTask details = collectDataTaskService.getDetails(item.getRelationId());
                item.setRelationContent(JSONObject.toJSONString(details));
            }
        }
        return getDataTable(list);
    }

    @ApiOperation("获取消息详情")
    @GetMapping("/api/v1/notice/{id}")
    public R<SysNotice> getInfo(@PathVariable Long id) {
        SysNotice sysNotice = sysNoticeService.selectNoticeById(id);
        if (sysNotice == null) {
            return R.fail(HttpStatus.NOT_FOUND, "当前消息不存在");
        } else {
            if (sysNotice.getRelationModule() != null && sysNotice.getRelationModule().equals(1)) {
                CollectDataTask collectDataTask = collectDataTaskService.getDetails(sysNotice.getRelationId());
                if (collectDataTask != null) {
                    sysNotice.setRelationContent(JSONObject.toJSONString(collectDataTask));
                }
            }
            if (sysNotice.getUserId().equals(0L) || sysNotice.getUserId().equals(SecurityUtils.getUserId())) {
                SysUserNotice userNotice = sysUserNoticeService.getByUserIdAndNoticeId(SecurityUtils.getUserId(), sysNotice.getNoticeId());
                if (userNotice == null) {
                    userNotice = new SysUserNotice();
                    userNotice.setUserId(SecurityUtils.getUserId());
                    userNotice.setNoticeId(sysNotice.getNoticeId());
                    userNotice.setStatus(1);
                    sysUserNoticeService.save(userNotice);
                } else {
                    if (!userNotice.getStatus().equals(1)) {
                        userNotice.setUserId(SecurityUtils.getUserId());
                        userNotice.setNoticeId(sysNotice.getNoticeId());
                        userNotice.setStatus(1);
                        sysUserNoticeService.updateById(userNotice);
                    }
                }
            } else {
                return R.fail(HttpStatus.NOT_FOUND, "当前消息不存在");
            }
            if (sysNotice.getRelationModule().equals(1)) {
                CollectDataTask details = collectDataTaskService.getDetails(sysNotice.getRelationId());
                sysNotice.setRelationContent(JSONObject.toJSONString(details));
            }
        }
        return R.ok(sysNotice);
    }

    @ApiOperation("设置已读/未读")
    @PutMapping("/api/v1/notice/{id}/read")
    public R read(@PathVariable Long id) {
        SysNotice sysNotice = sysNoticeService.selectNoticeById(id);
        if (sysNotice == null) {
            return R.fail(HttpStatus.NOT_FOUND, "当前消息不存在");
        }
        SysUserNotice userNotice = sysUserNoticeService.getByUserIdAndNoticeId(SecurityUtils.getUserId(), sysNotice.getNoticeId());
        if (userNotice == null) {
            userNotice = new SysUserNotice();
            userNotice.setUserId(SecurityUtils.getUserId());
            userNotice.setNoticeId(sysNotice.getNoticeId());
            userNotice.setStatus(1);
            sysUserNoticeService.save(userNotice);
        } else {
            if (userNotice.getStatus().equals(0)) {
                userNotice.setStatus(1);
            } else {
                userNotice.setStatus(0);
            }
            sysUserNoticeService.updateById(userNotice);
        }
        return R.ok();
    }

    @PutMapping("/api/v1/notice/setting")
    @ApiOperation("通知开关设置")
    public R updateSetting(@RequestBody @Valid NoticeSwitchBody body) {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        if (sysUser != null) {
            sysUser.setSysUpdateNoticeSwitch(body.getSysUpdateNoticeSwitch());
            sysUser.setTaskDeliveryNoticeSwitch(body.getTaskDeliveryNoticeSwitch());
            sysUser.setTaskReviewNoticeSwitch(body.getTaskReviewNoticeSwitch());
            userService.updateNoticeSwitch(sysUser);
        }
        return R.ok();
    }

    @GetMapping("/api/v1/notice/setting")
    @ApiOperation("获取通知开关设置")
    public R<NoticeSettingVO> getSetting() {
        Long userId = SecurityUtils.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        NoticeSettingVO data = new NoticeSettingVO();
        if (sysUser != null) {
            if (sysUser.getSysUpdateNoticeSwitch() != null) {
                data.setSysUpdateNoticeSwitch(sysUser.getSysUpdateNoticeSwitch());
            }
            if (sysUser.getTaskDeliveryNoticeSwitch() != null) {
                data.setTaskDeliveryNoticeSwitch(sysUser.getTaskDeliveryNoticeSwitch());
            }
            if (sysUser.getTaskReviewNoticeSwitch() != null) {
                data.setTaskReviewNoticeSwitch(sysUser.getTaskReviewNoticeSwitch());
            }
        }
        return R.ok(data);
    }
}
